package com.zsr.educenter.controller;

import com.google.gson.Gson;
import com.zsr.commonutils.util.JwtUtil;
import com.zsr.educenter.entity.UcenterMember;
import com.zsr.educenter.service.UcenterMemberService;
import com.zsr.educenter.utils.ConstantWxUtils;
import com.zsr.educenter.utils.HttpClientUtils;
import com.zsr.servicebase.exceptionhandler.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author zsr
 * @date 2021/6/19 23:26
 */
//@CrossOrigin
@Controller//注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    UcenterMemberService memberService;

    /**
     * 扫码成功的回调函数
     *
     * @param code  临时票据
     * @param state 用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
     * @return
     */
    @GetMapping("callback")
    public String callback(String code, String state) {
        //向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code);

        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
            //System.out.println("accessToken=============" + result);
            //{"access_token":"","expires_in":7200,"refresh_token":"","openid":"","scope":"snsapi_login","unionid":""}
        } catch (Exception e) {
            throw new BusinessException(20001, "获取access_token失败");
        }
        //解析json 获取access_token，openid
        Gson gson = new Gson();
        HashMap map = gson.fromJson(result, HashMap.class);
        String accessToken = (String) map.get("access_token");
        String openid = (String) map.get("openid");
        //查询数据库当前用用户是否曾经使用过微信登录
        UcenterMember member = memberService.getByOpenid(openid);
        if (member == null) {
            System.out.println("新用户注册");

            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo==========" + resultUserInfo);
            } catch (Exception e) {
                throw new BusinessException(20001, "获取用户信息失败");
            }

            //{"openid":"","nickname":"xs","sex":1,"language":"zh_CN","city":"","province":"","country":"CN","headimgurl":"","privilege":[],"unionid":""}
            //解析json
            HashMap<String, Object> mapUserInfo = gson.fromJson(resultUserInfo, HashMap.class);
            String nickname = (String) mapUserInfo.get("nickname");
            String headimgurl = (String) mapUserInfo.get("headimgurl");
            Integer sex = null;
            String sexString = mapUserInfo.get("sex").toString();
            if (!StringUtils.isEmpty(sexString)) sex = (int) Double.parseDouble(sexString);


            //向数据库中插入一条记录
            member = new UcenterMember();
            member.setNickname(nickname);
            member.setOpenid(openid);
            member.setAvatar(headimgurl);
            member.setSex(sex);
            memberService.save(member);
        }

        //TODO 登录
        //方法1. 存入cookie，但是会有跨域问题

        //方法2：JWT将信息传入token，通过路径传递Token给首页
        String jwtToken = JwtUtil.getJwtToken(member.getId(), member.getNickname());
        http:
//localhost:3000/login
        return "redirect:http://localhost:3000?token=" + jwtToken;
    }

    @GetMapping("login")
    public String genQrConnect(HttpSession session) {

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(20001, e.getMessage());
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "imhelen";
        System.out.println("state = " + state);

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                state);
        //http://localhost:8160/api/ucenter/wx/callback?code=041kOd000pIIUL1Z0K200zsFqp1kOd0L&state=imhelen
        //code 值，下一步拿着这个code值去请求wx提供的固定地址，得到accessToken令牌和openId(每个wx唯一的标识)
        //下一步拿着accessToken和openId去访问一个地址，获取扫码人的信息
        return "redirect:" + qrcodeUrl;
    }
}
